import {RichText, ScrollView, View} from '@tarojs/components';
import {Button, Checkbox, Uploader, Flex, Tag, ActionSheet, Popup, Empty} from "@taroify/core";
import { FilterOutlined, Plus, LabelOutlined } from "@taroify/icons";
import { useEffect, useState } from "react";
import { useCollectionSelector, useDispatchCollection } from "@/hooks/collection";
import { marked } from 'marked';
import Taro from '@tarojs/taro';
import {uploadFile} from "@/api/upload";
import {useDispatchTextBlock, useTextBlockSelector} from "@/hooks/textBlock";

export default function Index(props: { knowledge_base_uuid: string, note_collection_uuid: string }) {
  const { knowledge_base_uuid, note_collection_uuid } = props;
  const dispatchCollection = useDispatchCollection();
  const collections = useCollectionSelector(state => state.collection.collections);

  const dispatchTextBlock = useDispatchTextBlock();
  const textBlocks = useTextBlockSelector(state => state.textBlock.textBlocks);

  const [isNotePopupOpen, setIsNotePopupOpen] = useState(false);
  const [noteContent, setNoteContent] = useState("");

  const [noteActionVisible, setNoteActionVisible] = useState(false);
  const [selectNote, setSelectNote] = useState('');
  const handleNoteLongPress = (note_uuid: string) => {
    setSelectNote(note_uuid);
    setNoteActionVisible(true);
  };

  const handleNoteSheetClick = async (event: { value: string; }) => {
    if(!selectNote) return
    if (event.value === 'edit') {
      await Taro.showToast({
        title: '暂不支持',
        icon: 'none',
      });
    } else if (event.value === 'delete') {
      await dispatchTextBlock.removeTextBlock(selectNote)
      await Taro.showToast({
        title: '删除成功',
        icon: 'none',
      });
    }
    setNoteActionVisible(false);
  };

  const handleNoteClick = (note: string) => {
    setNoteContent(note);
    setIsNotePopupOpen(true);
  };

  const [collectionActionVisible, setCollectionActionVisible] = useState(false);
  const [selectCollection, setSelectCollection] = useState('');
  const handleCollectionLongPress = (collection_uuid: string) => {
    setSelectCollection(collection_uuid);
    setCollectionActionVisible(true);
  };
  const handleCollectionSheetClick = async (event: { value: string; }) => {
    if(!selectCollection) return
    if (event.value === 'edit') {
      await Taro.showToast({
        title: '暂不支持',
        icon: 'none',
      });
    } else if (event.value === 'delete') {
      await dispatchCollection.removeCollection(selectCollection)
      await Taro.showToast({
        title: '删除成功',
        icon: 'none',
      });
    }
    setCollectionActionVisible(false);
  };


  const onUpload = () => {
    Taro.chooseMessageFile({
      count: 9, // 一次选择一个文件
      type: 'file', // 文件类型
      extension: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'],
    }).then(async (res) => {
      const tempFiles = res.tempFiles;
      for (const file of tempFiles) {
        const file_url = await uploadFile(file.path);
        const collectionData = {
          knowledge_base_uuid: knowledge_base_uuid,
          name: file.name,
          file_url: file_url.url,
          status: 1
        }
        await dispatchCollection.addCollection(collectionData)
      }
    }).catch(async (err) => {
      console.error('文件选择失败:', err);
      await Taro.showToast({
        title: '文件选择失败',
        icon: 'none',
      });
    });
  };

  useEffect(() => {
    dispatchCollection.getCollectionDetail(note_collection_uuid);
    dispatchCollection.getAllCollections(knowledge_base_uuid)

    dispatchTextBlock.getAllTextBlocks(note_collection_uuid)
  }, [knowledge_base_uuid, note_collection_uuid]);


  return (
    <View style={{ height: '100%', width: '100%'}}>
      <View style={{padding:'10px', display: 'none'}}>
        {/* 添加来源按钮 */}
        <Uploader
          multiple
          onUpload={onUpload}
          style={{ width: '100%' }}
        >
          <Button variant='outlined' color='primary' icon={<Plus />} style={{ width: '100%' }} size='small'>
            上传文件
          </Button>
        </Uploader>
      </View>

      {/* 知识库列表 */}
      <View style={{padding: '10px', display: 'none'}}>
        <Tag color='primary'>来源</Tag>
        {collections?.items.map((collection) => {
          if (collection.uuid != note_collection_uuid)
            return (
              <Flex
                gutter={20}
                align='center'
                key={collection.uuid}
                style={{
                  borderBottom: '1px solid #f0f2f5',
                  padding: '20rpx'
                }}
              >
                <Flex.Item>
                  <FilterOutlined />
                </Flex.Item>
                {/* 文本部分 */}
                <Flex.Item
                  onLongPress={() => handleCollectionLongPress(collection.uuid)}
                  style={{
                    flex: 1,
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    marginRight: '10px'
                  }}
                >
                  {collection.name}
                </Flex.Item>

                {/* Checkbox 部分 */}
                <Flex.Item>
                  <Checkbox />
                </Flex.Item>
              </Flex>
            );
        })}
        {collections?.items.length === 0 &&
          <Empty>
            <Empty.Image />
            <Empty.Description>暂无文件，快去上传添加吧！</Empty.Description>
          </Empty>
        }
      </View>

      {/* 聊天笔记 */}
      <View style={{padding: '10px'}}>
        <Tag color='primary'>笔记</Tag>
        {textBlocks.items.map((text_block, index) => {
          return (
            <Flex
              gutter={20}
              align='center'
              key={index}
              style={{
                borderBottom: '1px solid #f0f2f5',
                padding: '20rpx'
              }}
            >
              <Flex.Item>
                <LabelOutlined />
              </Flex.Item>
              {/* 文本部分 */}
              <Flex.Item
                onLongPress={() => handleNoteLongPress(text_block.uuid)}
                onClick={() => handleNoteClick(text_block.content)}
                style={{
                  flex: 1,
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  marginRight: '10px'
                }}
              >
                {text_block.content}
              </Flex.Item>

              {/* Checkbox 部分 */}
              <Flex.Item>
                <Checkbox />
              </Flex.Item>
            </Flex>
          );
        })}
        {textBlocks.items.length === 0 &&
          <Empty>
            <Empty.Image />
            <Empty.Description>暂无笔记，快去聊天中添加吧！</Empty.Description>
          </Empty>
        }
      </View>


      <Popup
        open={isNotePopupOpen}
        lock={false}
        placement='bottom'
        style={{height: '60%', border: '1px solid #f0f2f5'}}
        onClose={() => setIsNotePopupOpen(false)}
      >
        <ScrollView >
          <View style={{ wordWrap: 'break-word', height: '100%', padding: '30rpx'}}>
            <RichText nodes={marked(noteContent)} style={{ fontSize: '30rpx' }} />
          </View>
        </ScrollView>
      </Popup>

      <ActionSheet
        style={{width: '100vw'}}
        cancelText='取消'
        open={noteActionVisible}
        onSelect={handleNoteSheetClick}
        onCancel={() => setNoteActionVisible(false)}
        onClose={() => setNoteActionVisible(false)}
        actions={[
          { name: '编辑', value: 'edit', style:{ color: '#1890ff'} },
          { name: '删除', value: 'delete', style:{ color: '#ff4d4f'} },
        ]}
      />

      <ActionSheet
        style={{width: '100vw'}}
        cancelText='取消'
        open={collectionActionVisible}
        onSelect={handleCollectionSheetClick}
        onCancel={() => setCollectionActionVisible(false)}
        onClose={() => setCollectionActionVisible(false)}
        actions={[
          { name: '删除', value: 'delete', style:{ color: '#ff4d4f'} },
        ]}
      />
    </View>
  );
}
